package com.bjb.vr.remote.ws.rabbitmq.handler.impl;

import com.alibaba.fastjson.JSONObject;
import com.bjb.vr.common.service.ResDeviceService;
import com.bjb.vr.common.utils.RedisUtil;
import com.bjb.vr.remote.ws.rabbitmq.constants.MessageActionConstants;
import com.bjb.vr.remote.ws.rabbitmq.entity.RabbitWebSocketMsg;
import com.bjb.vr.remote.ws.rabbitmq.handler.MessageHandler;
import com.bjb.vr.remote.ws.redis.constants.RedisConstants;
import com.bjb.vr.remote.ws.websocket.vo.Message;
import com.bjb.vr.remote.ws.websocket.websocket.WebSocketMsgHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @version 1.0.0
 * @description:
 * @author: caihaibo
 * @createDate: 2022/3/29
 */
@Component
@Slf4j
public class CvrLockStateMessageHandler implements MessageHandler {

    @Autowired
    ResDeviceService resDeviceService;

    @Autowired
    RedisUtil redisUtil;

    final String  LOCK_KEY = "res_device_lock_state";

    @Override
    public void process(RabbitWebSocketMsg rabbitWebSocketMsg) {
        String dbLockKey = RedisConstants.WEBSOCKET_DB_OP_LOCK_KEY + LOCK_KEY+ rabbitWebSocketMsg.getDeviceId();

        JSONObject jsonObject = JSONObject.parseObject(rabbitWebSocketMsg.getMsg());

        Message message = JSONObject.toJavaObject(jsonObject, Message.class);

        if(message.getAction().equals(MessageActionConstants.MESSAGE_ACTION_LOCK_STATE)){
            log.info("处理锁定状态上传信息");
//            WebSocketMsgHandler.sendAdmin(rabbitWebSocketMsg);
            JSONObject _jsonObject = JSONObject.parseObject(message.getCommand().getParameter());
            String value = String.valueOf(System.currentTimeMillis());

            if(redisUtil.lock(dbLockKey,value, RedisConstants.WEBSOCKET_DB_OP_LOCK_KEY_EXPIRE_TIME)) {
                resDeviceService.updateResDeviceLockStateByUdid(message.getCommand().getUdid(), _jsonObject.getInteger("lockState"));
                redisUtil.unlock(dbLockKey, value);
            }
//            try{
//                Thread.sleep(100);
//                WebSocketMsgHandler.sendAdmin(rabbitWebSocketMsg);
//            }catch(Exception ex){
//                ex.printStackTrace();
//                log.error("处理锁定状态上传信息出错,消息 " +  rabbitWebSocketMsg ,ex);
//            }
        }
    }
}
